package com.settlement.system.controller;

import com.settlement.system.common.util.StringUtils;
import com.settlement.system.config.WxPayConfig;
import com.settlement.system.service.SysPayOrderService;
import com.yungouos.pay.util.PaySignUtil;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

@RestController
@RequestMapping("/api/wxpay")
@RequiredArgsConstructor
public class WxPayController {

    private final static Logger logger = LoggerFactory.getLogger(WxPayController.class);

    private final SysPayOrderService sysPayOrderService;

    /**
     * 微信支付回调接口
     */
    @RequestMapping("/callback/notify")
    @Operation(summary = "微信支付回调通知")
    public String notify(@RequestParam Map<String, String> data, HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("接受到支付结果回调");
            logger.info(data.toString());
            String payChannel = data.get("payChannel");
            String attach = data.get("attach");
            if (StringUtils.isBlank(payChannel)) {
                return "PAY CHANNEL IS NULL";
            }
            String key = WxPayConfig.key;
            boolean sign = PaySignUtil.checkNotifySign(request, key);
            logger.info("签名验证：" + sign);
            if (!sign) {
                return "SIGN FAIL";

            }
            String outTradeNo = data.get("outTradeNo");
            String payNo = data.get("payNo");
            String time = data.get("time");
            String code = data.get("code");
            // 检查付款状态
            if (Integer.parseInt(code) != 1) {
                return "PAY FAIL";
            }
            // 更新订单状态
            boolean success = sysPayOrderService.paySuccess(outTradeNo, payNo, time);
            if (!success) {
                return "FAIL";
            }
            PrintWriter out = response.getWriter();
            out.print("SUCCESS");
            out.flush();
            out.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
